'use strict';

const {
	Controller
} = require('uni-cloud-router');

module.exports = class TestController extends Controller {
	
	// 格式化日期
	date() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		
		const nowdate = Date.now();
		const utc8date = this.service.utils.toDateUTC8(Date.now());
		response.datas = {
			now: nowdate,
			nowformat: this.service.utils.formatdate(nowdate, 'yyyy年MM月dd日 hh:mm:ss'),
			utc8: utc8date,
			utc8format: this.service.utils.formatdate(utc8date, 'yyyy年MM月dd日 hh:mm:ss'),
		} 
		response.code = 0;
	
		return response;
	}
	
	desz() {
		const response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		response.datas.desz = this.service.utils.desz('18825281536');
		
		return response;
	}
	
	async usersMobileLogin() {
		let response = {
			result: 0
		};
		const start = new Date().getTime();
		
		// 批量处理用户数据
		let userRes = await this.db.collection('uni-id-users')
			.where({ username: this.db.command.exists(true), role: this.db.command.all(['member']) })
			.orderBy('register_date', 'asc')
			.limit(500)
			.get();
		let createTime = 0;
		
		do {
		    userRes.data && userRes.data.forEach(async (x) => {
		    	await this.db.collection('uni-id-users').doc(x._id).update({
		    		mobile: x.username,
		    		mobile_confirmed: 1
		    	});
		    	
		    	response.result++;
		    	createTime = x.register_date;
		    });
			
			userRes = await this.db.collection('uni-id-users')
				.where({ username: this.db.command.exists(true), role: this.db.command.all(['member']), register_date: this.db.command.gt(createTime) })
				.orderBy('register_date', 'asc')
				.limit(500)
				.get();
		    
		} while (userRes.data && userRes.data.length > 0);
		
		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.duration = end - start;
		
		return response;
	}
	
}
